package com.taobaostore.common;

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

/**
 * 响应返回
 * @author xzp
 *
 * @param <T>
 */
// 使用@JsonSerialize注解后:比如我只传了status msg和data就不会被序列化成json,便不会出现在json中(null的属性key也会消失)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable {
	private static final long serialVersionUID = 1L;
	private int status;// 返回状态
	private String msg;// 返回附带信息
	private T data;// 返回附带对象

	//使用@JsonIgnore注解之后不会被该方法不会被序列化成json
	@JsonIgnore
	public boolean isSuccess() {
		return this.status == ResponseCode.SUCCESS.getCODE();
	}

	public int getStatus() {
		return status;
	}

	public String getMsg() {
		return msg;
	}


	public T getData() {
		return data;
	}


	// 响应成功
	public static <T> ServerResponse<T> createBySuccess(){
		return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE());
	}
	public static <T> ServerResponse<T> createBySuccess(String msg){
		return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE(), msg);
	}
	public static <T> ServerResponse<T> createBySuccess(T data){
		return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE(),data);
	}
	public static <T> ServerResponse<T> createBySuccess(String msg,T data){
		return new ServerResponse<T>(ResponseCode.SUCCESS.getCODE(), msg,data);
	}

	// 响应失败
	public static <T> ServerResponse<T> createByError(){
		return new ServerResponse<T>(ResponseCode.ERROR.getCODE());
	}
	public static <T> ServerResponse<T> createByError(String msg){
		return new ServerResponse<T>(ResponseCode.ERROR.getCODE(), msg);
	}
	public static <T> ServerResponse<T> createByError(T data){
		return new ServerResponse<T>(ResponseCode.ERROR.getCODE(), data);
	}
	public static <T> ServerResponse<T> createByError(String msg,T data){
		return new ServerResponse<T>(ResponseCode.ERROR.getCODE(), msg,data);
	}
	// 自定义错误信息(登录错误,参数错误等)
	public static <T> ServerResponse<T> createByError(int errorCode,String errorMsg){
		return new ServerResponse<T>(errorCode, errorMsg);
	}

	private ServerResponse(int status) {
		this.status = status;
	}
	private ServerResponse(int status,String msg) {
		this.status = status;
		this.msg = msg;
	}
	private ServerResponse(int status,T data) {
		this.status = status;
		this.data = data;
	}
	private ServerResponse(int status,String msg,T data) {
		this.status = status;
		this.msg = msg;
		this.data = data;
	}
	@Override
	public String toString() {
		return "ServerResponse [status=" + status + ", msg=" + msg + ", data=" + data + "]";
	}
}
